<template>
	<view class="view_step1">
		<button class="search_ble_btn" @click="searchBle">搜索蓝牙</button>
		<view class="ble_list">
			<button class="ble_item" v-for="(item,index) in devices" @click="onConn(item)" :key="index+'_btn'" >
				<span>{{item.name}}</span>
				<template v-if="params.connId == item.deviceId">
					<uni-icons :key="item.deviceId+'_cycle'" v-if="params.connStatus == 1" class="icon_status" type="spinner-cycle"></uni-icons>
					<template  v-else-if="params.connStatus == 2" class="icon_status"></template>
					<uni-icons :key="item.deviceId+'_empty'" v-else="params.connStatus == 0" class="icon_status" type="checkmarkempty"></uni-icons>
				</template>
			</button>
		</view>
	</view>
</template>

<script>
import { showConfirm } from '../../../../utils/common';
	export default {
		props:{},
		emits:['close'],
		data() {
			return {
				blePlatform:uni.requireNativePlugin("TH-PlatformBLE"),
        params:{
          connId:'',
					connStatus:''
        },
				textValue:'',
        formProps:{
          labelWidth:85
        },
        formCols:[
          {
            label:'链接蓝牙',
            key:'connId',
            type:'slot',
            rules: [{ required: true, errorMessage: '请选择蓝牙设备'}],
            props:{
              placeholder:'请选择蓝牙设备',
              clear: true
            }
          },
          {
            label:'链接状态',
            key:'connStatus',
            type:'data-checkbox',
            props:{
              placeholder:'',
              clear: true,
              localdata:[
								{ text: '已连接', value: 0 }, 
								{ text: '未连接', value: 1 }
							]
            }
          },
        ],
				devices:[]
			};
		},
    created(){
			this.$nextTick(()=>{
				this.initBleStatus()
				this.searchBle()
			})
    },
		methods:{
			initBleStatus(){
				const that = this
				const { printDevice,printStatus } =  this.$store.getters || {}
				that.params.connId = printDevice?.deviceId || ''
				if(that.params.connId){
					that.params.connStatus = (printStatus || printStatus === 0)? printStatus: 2
					if(that.params.connStatus === 0){
						that.stopFindBule()
						that.devices.push(printDevice)
					}
				}
				that.blePlatform.connState((ret) => {//新增方法 (蓝牙连接的状态回调)
					// 0 已连接 1连接中 2 取消链接
					that.params.connStatus = ret
					that.$store.commit('SET_PRINT_STATUS',ret)
					if(that.params.connStatus == 0){
						that.stopFindBule()
					}
				});
			},
			destroyed () {
				uni.closeBLEConnection({
						deviceId: this.params.connId,
						success(res) {
							console.log(res)
						}
				})
			},
			searchBle() {
				console.log("initBule")
				var that = this
				uni.openBluetoothAdapter({
					success(res) {
            that.onDevice()
            uni.getBluetoothAdapterState({
              success: function(res) {
                console.log('蓝牙状态',res)
                if (res.available) {
                  if (res.discovering) {
                    that.stopFindBule()
                  }
                  //搜索蓝牙 - 开始搜寻附近的蓝牙外围设备
                  uni.startBluetoothDevicesDiscovery({
                    success(res) {
                      console.log('开始搜寻附近的蓝牙外围设备',res)
                    }
                  })
                } else {
                  console.log('本机蓝牙不可用')
                }
              },
            })
					},
          fail(res){
            that.$modal.showToast('请先打开蓝牙')
          }
				})
			},
      // 监听寻找到新设备的事件
			onDevice(){
				console.log("监听寻找到新设备的事件---------------")
        const that = this
				uni.onBluetoothDeviceFound(function (devices) {
					var re = JSON.parse(JSON.stringify(devices))
					console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
						let name = re.devices[0].name		
						if (name != "未知设备" && name != "" && name != "null") {
							let deviceId = re.devices[0].deviceId
							const itemInfo = that.devices.find((item)=>item.deviceId === deviceId)
							if(!itemInfo){
								that.devices.push({
										text:name,
										name: name,
										value:deviceId,
										deviceId: deviceId,
										services: []
								})
							}
						}
				})
				setTimeout(()=>{
					if(!this.devices.length){
						showConfirm('部分机型需要开启GPS定位功能才能搜索到附近的蓝牙设备',{
							confirmText:'知道了',
							showCancel:false
						}).then(()=>{
							this.$emit('close')
						})
					}
				},3000)
			},
			// 停止搜寻附近的蓝牙外围设备
			stopFindBule() {
				uni.stopBluetoothDevicesDiscovery()
			},
      // 连接蓝牙
			onConn(item) {
				try {
					const that = this
					let deviceId = item.deviceId
					that.blePlatform.bluetoothConn(deviceId);
					that.params.connId = deviceId
					uni.createBLEConnection({
						deviceId: deviceId,
						fail:(res)=>{
							console.log('sss',res)
						},
						complete:(res)=>{
							if (res.errMsg == "createBLEConnection:ok") {
								setTimeout(function() {
									that.getBLEServices(deviceId)
								}, 2000)
							} else {
								console.log('连接蓝牙',res)
							}
							//连接成功 关闭搜索
							that.stopFindBule()
						},
					})
				} catch (error) {
					console.log('连接蓝牙-error',error)
					
				}
			},
      // 获取当前链接蓝牙设备的所有服务
			getBLEServices(_deviceId) {
				var that = this;
				let deviceId = _deviceId
				console.log("获取蓝牙设备所有服务(service)。---------------")
				uni.getBLEDeviceServices({
					deviceId: deviceId,
					complete(res) {
						for (var s = 0; s < res.services.length; s++) {
							let serviceId = res.services[s].uuid
							console.log('serviceId',serviceId)
							uni.getBLEDeviceCharacteristics({
								deviceId: deviceId,  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
								serviceId: serviceId, 	// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
								success(res) {
									var re = JSON.parse(JSON.stringify(res))
									console.log('deviceId = [' + deviceId + ']  serviceId = [' + serviceId + ']')
									for (var c = 0; c < re.characteristics.length; c++) {
										if (re.characteristics[c].properties.write == true) {
											let uuid = re.characteristics[c].uuid
											for (var index in that.devices) {
												if (that.devices[index].deviceId == deviceId) {
													that.devices[index].services.push({
														serviceId: serviceId,
														characteristicId: uuid
													})
													that.$store.commit('SET_PRINT_DEVICE',that.devices[index])
													break
												}
											}
											console.log(JSON.stringify(that.devices))
										}
									}
								}
							})
						}
					},
					fail(res) {
						console.log(res)
					},
				})

			},
		}
	}
</script>

<style lang="scss">
.view_step1{
	.search_ble_btn{
		font-size: 30rpx;
		line-height: 80rpx;
	}
	.ble_list{
		margin-top: 40rpx;
		.ble_item{
			font-size: 38rpx;
			line-height: 80rpx;
			color: #0081FF;
			&+.ble_item{
				margin-top: 20rpx;
			}
			.icon_status{
				margin-left: 10rpx;
				color: #0081FF;
				&::before{
					color: #0081FF;
				}
			}
		}
	}
	.ble_loading{
		position: relative;
		width: 35px;
		height: 35px;
		perspective: 800px;
		transform-style: preserve-3d;
		transition: all 0.2s ease-out;
	}
}

</style>
